import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import type { ConfigEnv, UserConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//mock插件提供方法
// https://vite.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd())

  return {
    resolve: {
      alias: {
        '@': '/src',
        '@views': '/src/views',
        '@components': '/src/components',
        '@api': '/src/api',
        '@utils': '/src/utils',
        '@types': '/src/types',
        '@styles': '/src/styles',
        '@hooks': '/src/hooks',
        '@store': '/src/store',
        '@router': '/src/router',
      },
    },
    plugins: [
      vue(),
      // 配置SVG图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        dts: true, // 生成类型声明文件
      }),
      Components({
        resolvers: [ElementPlusResolver()],
        dts: true, // 生成类型声明文件
      }),

      viteMockServe({
        mockPath: 'mock', // mock文件目录
        enable: command === 'serve', // 是否启用mock
        watchFiles: true, // 监听文件变化
        ignore: /^\_/, // 忽略的文件
        configPath: './mock/mock.config.ts',
      }),
    ],

    // 服务器配置
    server: {
      host: true,
      port: 5173,
      proxy: {
        [env.VITE_BASE_API]: {
          target: 'http://localhost:3000',
          changeOrigin: true,
          rewrite: (path) =>
            path.replace(new RegExp('^' + env.VITE_BASE_API), ''),
        },
      },
    },

    // 构建配置
    build: {
      outDir: 'dist',
      // 使用 esbuild 作为压缩工具，避免 terser 配置问题
      minify: 'esbuild',
      // 简化配置，使用 esbuild 的默认配置
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ['vue', 'element-plus'],
          },
        },
      },
    },

    // CSS 配置
    css: {
      preprocessorOptions: {
        scss: {
          // 自动导入全局 SCSS 变量和混入
          additionalData: `@use "@/styles/variables.scss" as *; @use "@/styles/mixins.scss" as *;`,
        },
      },
    },
  }
})
